function[x,output]=agent1maxrho_rov_het_06_Mar(x0,index,ewsb,waut,bind,Y,n,beta,rho,rho_rov,ScaleRov,cfirstbest,rr)

i=index(1);
j=index(2);

lb=[];
ub=[];

if bind==1     
    if rr(1)==1
         
    x=cfirstbest(1,j,1);
    output(1)=utility(rho,cfirstbest(1,j,1))+beta*ewsb(1,j,1);
    output(2)=utility(rho_rov,cfirstbest(1,j,1))+beta*ewsb(1,j,2);
    output(3)=1;
    elseif rr(1)>1
    ub=cfirstbest(rr(1),index(2),1);
    lb=cfirstbest(rr(1)-1,index(2),1);
    end
elseif bind==2
    if rr(end)==n %%% see notes for bind=1 above.
    x=cfirstbest(i,j,1);
    output(1)=utility(rho,cfirstbest(n,j,1))+beta*ewsb(n,j,1);
    output(2)=utility(rho_rov,cfirstbest(n,j,1))+beta*ewsb(n,j,2);
    output(3)=1;
    elseif rr(end)<n
    lb=cfirstbest(rr(end),index(2),1);
    ub=cfirstbest(rr(end)+1,index(2),1);
    end
end

%%%%find consumption for which participation constraint binds with equality
if size(lb)>0

XX=[lb ub];
%%in case lb, ub 
if bind==1
YY(1)=utility(rho,cfirstbest(rr(1)-1,j,1))+beta*ewsb(rr(1)-1,j,1);
YY(2)=utility(rho,cfirstbest(rr(1),j,1))+beta*ewsb(rr(1),j,1);
%%%find where it binds with equality
x=interp1(YY-waut(j,1),XX,0);
output(1)=interp1(XX,YY,x);

%%%%find the new continuation values
cons = x(1);
wint(2)=interp1(cfirstbest(:,j,1),ewsb(:,j,2),x);
output(2)=utility(rho_rov,(Y(j)-cons)/ScaleRov)+beta*wint(2);

%%%check that agent 2's participation constraint is satisfied
if output(2)>=waut(j,2)
    output(3)=1;
else
    output(3)=-2;
end

elseif bind==2

YY(1)=utility(rho_rov,cfirstbest(rr(end),j,2))+beta*ewsb(rr(end),j,2);
YY(2)=utility(rho_rov,cfirstbest(rr(end)+1,j,2))+beta*ewsb(rr(end)+1,j,2);
%%%find where it binds with equality
x=interp1(YY-waut(j,2),XX,0);
output(2)=interp1(XX,YY,x);

%%%%find the new continuation values
cons = x(1);

wint(1)=interp1(cfirstbest(:,j,1),ewsb(:,j,1),x);


output(1)=utility(rho,cons)+beta*wint(1);


%%%check that agent 1's participation constraint is satisfied (this is done
%%%outside the loop)
        %if output(1)>=waut(j,1)
        %output(3)=1;
        %else
        %output(3)=-2;
        %end
        output(3)=1;
    end

end

end